import dayjs from 'dayjs';
import utc from 'dayjs/plugin/utc';
dayjs.extend(utc);
import useSWR from 'swr';
import fetcher from '../api/fetcher';
import {REFRESH_INTERVAL,WEATHER_URL,WEATHER_PRIVATE_KEY,ICON_PREFIX} from '../config/index'

export function  useWeather({exclude, weatherType}) {
  // TODO 暂时固定杭州 经纬度
  const apiEndpoint = `?lat=30.235559463500977&lon=120.15888977050781&&lang=zh_cn&units=metric&exclude=${exclude}&APPID=${WEATHER_PRIVATE_KEY}`;

  let weatherData = null
  let weatherError = null
  const { data, error } = useSWR(
    `${WEATHER_URL}${apiEndpoint}`,
    fetcher,
    { refreshInterval: REFRESH_INTERVAL} // 1分钟请求一次
  );
  // 获取到数据做缓存处理, 只有数据变化后才会再次获取
  // if (data && !error) {
  //   weatherData = data
  //   weatherError = error
  //   console.log('获取新数据并设置缓存')
  //   localStorage.setItem('cacheData', JSON.stringify(data));
  // } else if (error) { // 只有发送网络错误时才读取缓存

  //   if (localStorage.getItem('cacheData')) {
  //     console.log('获取数据缓存')
  //     weatherData = JSON.parse(localStorage.getItem('cacheData'));
  //     weatherError = undefined
  //   }
  // }
  // 第一次数据缓存下来。解决sw注册时fetch无法缓存
  if (data) {
    if ('caches' in window && !localStorage.getItem('firstGetData')) {
      localStorage.setItem('firstGetData', '1')
      // 伪造 request/response 数据
      caches.open('weather-api-response').then((cache) => {
        cache.put(`${WEATHER_URL}${apiEndpoint}`, new Response(JSON.stringify(data), { status: 200 }));
      });
    }
  }
  weatherData = data
  weatherError = error
  // console.log('weatherError', weatherError, 'weatherData', weatherData)
    
    if(weatherData === null) return
    
    let xData = []
    let yData = []
    return {
      current:  weatherData && (weatherData.current ? mapResponseProperties(weatherData.current, {
        type:  'current',
        timeZone: weatherData.timezone_offset
      }) : null),
      daily: weatherData && ( weatherData.daily && Object.entries(weatherData.daily).length
      ? weatherData.daily.slice(1)
          .map((item) => {
            return mapResponseProperties(item, {
              type:  'daily',
              timeZone: weatherData.timezone_offset
            })
          })
      : []),
      hourly:  weatherData && ( weatherData.hourly && Object.entries(weatherData.hourly).length
      ? weatherData.hourly.slice(0,12)
          .map((item)=>{
            const res =  mapResponseProperties(item,{
              type:  'hourly',
              timeZone: weatherData.timezone_offset
            })
            res.currentHour && xData.push(res.currentHour)
            res.temperature && yData.push(res.temperature)
            return res
          })
      : []),
      hourEcharts: {
        xData: xData,
        yData: yData
      },
      isLoading: !weatherData && !weatherError,
      isError: weatherError,
    
  }

}

function mapResponseProperties(data, {
  type, timeZone
}) {
  const mapped = {
    currentTime: '', // 当前时间
    currentHour: '', // 当前小时
    currentWeek: '', // 当前星期
    date: data.dt, // 日期（时间戳形式）
    humidity: data.humidity, // 湿度
    feels_like: data.feels_like  && Math.round(data.feels_like),// 体感温度
    icon_id: data.weather && data.weather[0].id,
    sunrise: data.sunrise,
    sunset: data.sunset,
    timezone: timeZone / 3600, // convert from seconds to hours
    temperature: data.temp  && Math.round(data.temp), // 温度（四舍五入）
    wind_speed: Math.round(data.wind_speed * 3.6), // convert from m/s to km/h (风速)
    description: data.weather && data.weather[0].description, // 天气描述
    weatherIcon: '', // icon图片
    isDay: false, // 是否是白天
  };
  if (data.weather && data.weather[0].icon) {
    mapped.weatherIcon =
    ICON_PREFIX + data.weather[0].icon + '@4x.png';
  }

  if (mapped.date) {
    const time = dayjs
     .utc(dayjs.unix(mapped.date))
     .utcOffset(mapped.timezone)
     mapped.currentTime = time.format()
     mapped.currentHour = time.format('h a');
     mapped.currentWeek = time.format("ddd")
  }
  if (mapped.sunset || mapped.sunrise) {
    mapped.sunrise = dayjs
      .utc(dayjs.unix(mapped.sunrise))
      .utcOffset(mapped.timezone)
      .format();
    mapped.sunset = dayjs
      .utc(dayjs.unix(mapped.sunset))
      .utcOffset(mapped.timezone)
      .format();
      // 是否是白天
    mapped.isDay =
    mapped.currentTime  > mapped.sunrise && mapped.currentTime  < mapped.sunset
        ? true
        : false;
  }

  if (data.temp && data.temp.min && data.temp.max) {
    mapped.max = Math.round(data.temp.max);
    mapped.min = Math.round(data.temp.min);
  }


  // remove undefined fields
  Object.entries(mapped).map(
    ([key, value]) => value === undefined && delete mapped[key],
  );

  return mapped;
}
